package tech.aistar.prj.util;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;

public class MybatisUtil {
    //相当于jdbc中的数据源[连接池] - 重量级的对象 - 创建和销毁的成本比较高
    //比较吃内存.保证在整个应用程序中 - 单例的
    private static SqlSessionFactory factory = null;

    //通过静态代码块
    static{
        //加载mybatis-config.xml进内存了,如果配置了mappers,那么映射文件也会被加载到内存.
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            factory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * SqlSession - 线程不安全的对象, 每个线程应该拥有自己的SqlSession对象
     * Connection+一级缓存
     * @return
     */
    public static SqlSession getSession() throws SQLException{
        return factory.openSession();
    }

    public static void close(SqlSession sqlSession){
        if(sqlSession!=null){
            sqlSession.close();
        }
    }
}


